//
//  DFUserViewController.m
//  DFront
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 xuzenghui. All rights reserved.
//

#import "DFUserViewController.h"
#import "DFUserCollectionController.h"
#import "FMDatabase.h"
#import "DFSignlTon.h"
#import "UIImage+ImageEffects.h"
#import "DFUserSuggestController.h"
#import "SDImageCache.h"
@interface DFUserViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong)UIImageView *imgProfile;
@property (nonatomic,strong)UIAlertController *alertController;
@property (nonatomic,strong)UIView *nightview;

@end

@implementation DFUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//  夜间模式View
    _nightview = [[UIView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    _nightview.backgroundColor = [UIColor blackColor];
    _nightview.userInteractionEnabled = NO;
    _nightview.alpha = 0;
    [[[UIApplication sharedApplication] keyWindow] addSubview:_nightview];

    self.view.backgroundColor = [UIColor whiteColor];
   
    self.dataBaseArr = [NSMutableArray arrayWithObjects:@"我的收藏",@"清除缓存",@"夜间模式",@"省流量模式",@"建议反馈",@"关于我们", nil];
    self.navigationController.navigationBar.hidden = YES;
    // Do any additional setup after loading the view.
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    
    self.mainTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.mainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"my"];
     
    _imgProfile = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"84780765.jpg"]];
    _imgProfile.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight / 3 );
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight / 3 + 64)];
    [self.view addSubview:_imgProfile];
    self.mainTableView.tableHeaderView = headerView;
    self.mainTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.mainTableView];
    
    UIView *TopView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 20)];
    TopView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:TopView];
    self.titleLab.text = @"用户设置";
    self.titleLab.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:self.topView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataBaseArr.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"my" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.textLabel.text = self.dataBaseArr[indexPath.row];
    
    NSArray *arr = @[@"iconfont-shoucangB",@"iconfont-qingchuhuancun",@"iconfont-yejianqing",@"iconfont-ttpodicon",@"iconfont-fankui",@"iconfont-guanyuwomen"];
    
    cell.imageView.image = [UIImage imageNamed:arr[indexPath.row]];
    if (indexPath.row == 2) {
        UISwitch *swit = [[UISwitch alloc]initWithFrame:CGRectMake(kScreenWidth - 80, 6, 40, 30)];
        [swit addTarget:self action:@selector(swithToNight:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:swit];
    }
    if (indexPath.row == 3) {
        UISwitch *swit = [[UISwitch alloc]initWithFrame:CGRectMake(kScreenWidth - 80, 6, 40, 30)];
        [swit addTarget:self action:@selector(saveMode:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:swit];
    }
    return cell;
}

- (void)swithToNight:(UISwitch*)switView
{
     DFSignlTon *signlTon = [DFSignlTon shareInstance];
    if (switView.selected == NO) {
       _nightview.alpha = 0.5;
        switView.selected = YES;
        signlTon.nightmode = nightModeYes;
    }else
    {
        switView.selected = NO;
        _nightview.alpha = 0;
        signlTon.nightmode = nightModeDefault;
    }
}

- (void)saveMode:(UISwitch*)switView
{
    DFSignlTon *signlTon = [DFSignlTon shareInstance];
    if (switView.selected == NO) {
        switView.selected = YES;
        signlTon.savemode = SaveModeYes;
    }else
    {
        switView.selected = NO;
        signlTon.savemode = SaveModeDefault;
    }
}
//
- (void)updateImg {
    CGFloat yOffset = self.mainTableView.contentOffset.y;
    if (yOffset <= 0) {
        CGFloat factor =3 * ((ABS(yOffset)+kScreenHeight / 3)*kScreenWidth)/kScreenHeight;
        CGRect f = CGRectMake(-(factor-kScreenWidth)/2, 64, factor, kScreenHeight / 3+ABS(yOffset));
        self.imgProfile.frame = f;
    } else {
        CGRect f = self.imgProfile.frame;
        f.origin.y = -yOffset + 64;
        self.imgProfile.frame = f;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self updateImg];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        DFUserCollectionController *collectionController = [[DFUserCollectionController alloc]init];
        CATransition* transition = [CATransition animation];
        transition.duration = 0.5;
        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type = kCATransitionFade;//kCATransitionMoveIn;//kCATransitionFade;  //, kCATransitionPush, kCATransitionReveal, kCATransitionFade
        //transition.subtype = kCATransitionFromTop; //kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom
        [self.navigationController.view.layer addAnimation:transition forKey:nil];
        [self.navigationController pushViewController:collectionController animated:NO];
}
    
//  清空缓存数据
    if (indexPath.row == 1) {
        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"DFront.db"];
        FMDatabase *database = [FMDatabase databaseWithPath:filePath];
        if ([database open]) {
            NSLog(@"数据库打开成功");
        }
        
        [database executeUpdate:@"drop table menu"];
        
        _alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"清除%.2fM缓存",[DFUserViewController folderSizeAtPath:nil]] preferredStyle:UIAlertControllerStyleAlert];
        [DFUserViewController clearCache:nil];
        [self presentViewController:_alertController animated:YES completion:nil];
        [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(alertControllerDismiss) userInfo:nil repeats:NO];
    }
//  建议与反馈
    if
        (indexPath.row == 4) {
        DFUserSuggestController *suggestController = [[DFUserSuggestController alloc]init];
        
        [self.navigationController pushViewController:suggestController animated:NO];
    }
    if (indexPath.row == 5) {
        [self authorshow:nil];
    }
}

- (void)alertControllerDismiss
{
    [_alertController dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

+(float)folderSizeAtPath:(NSString *)path{
//    NSFileManager *fileManager=[NSFileManager defaultManager];
       float folderSize;
//    if ([fileManager fileExistsAtPath:path]) {
//        NSArray *childerFiles=[fileManager subpathsAtPath:path];
//        for (NSString *fileName in childerFiles) {
//            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
//            folderSize +=[FileService fileSizeAtPath:absolutePath];
//        }
        //SDWebImage框架自身计算缓存的实现
        folderSize = [[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
        return folderSize;
//    }
//    return 0;
}

+(float)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
}

+(void)clearCache:(NSString *)path{
//    NSFileManager *fileManager=[NSFileManager defaultManager];
//    if ([fileManager fileExistsAtPath:path]) {
//        NSArray *childerFiles=[fileManager subpathsAtPath:path];
//        for (NSString *fileName in childerFiles) {
//            //如有需要，加入条件，过滤掉不想删除的文件
//            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
//            [fileManager removeItemAtPath:absolutePath error:nil];
//        }
//    }
    [[SDImageCache sharedImageCache] clearDisk];
}

- (void)authorshow:(UIButton *)sender
{
    UIAlertController *alertController2 = [UIAlertController alertControllerWithTitle:@"＝＝＝＝＝＝版权所有＝＝＝＝＝＝"message:@"APP黑人开发组" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction2 = [UIAlertAction actionWithTitle:@"873557329@qq.com" style:(UIAlertActionStyleDefault) handler:nil];
    UIAlertAction *okAction2 = [UIAlertAction actionWithTitle:@"710776987@qq.com" style:(UIAlertActionStyleDefault) handler:nil];
    UIAlertAction *deleateAction2 = [UIAlertAction actionWithTitle:@"862184725@qq.com" style: (UIAlertActionStyleDefault) handler:nil];
    UIAlertAction *okAction3 = [UIAlertAction actionWithTitle:@"版本号1.01" style:(UIAlertActionStyleDestructive) handler:nil];
    UIAlertAction *deleateAction3 = [UIAlertAction actionWithTitle:@"返回" style: (UIAlertActionStyleDefault) handler:nil];
    
    [alertController2 addAction:cancelAction2];
    [alertController2 addAction:okAction2];
    [alertController2 addAction:deleateAction2];
    [alertController2 addAction:okAction3];
    [alertController2 addAction:deleateAction3];
    [self presentViewController:alertController2 animated:YES completion:nil];
}







/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
